$(document).ready(function () {
	document.addEventListener("deviceready", onDeviceReady, false);
	getDataFromServer();
	var _book_id;
	var _data;
});
function getDataFromServer() {
	try {
        $.ajax({
            url: "http://phanhuutho.com/thesis/test",
            type: 'POST',
            dataType: 'json',
            error: function (data) {
                alert("App launch error", data);
            },
            success: function (data) {
                alert("App launch success", data);
                _data = data;
                loadMyBook();
            }
        });
    } catch (err) {
        // err
    }
}
function loadMyBook() {
	$('#mybook').empty();
	for(var i = 0; i < window.localStorage.length; i++) {
		var book_id = window.localStorage.key(i);
		var book = JSON.parse(window.localStorage.getItem(book_id));
		
		if (true == checkUpdate(book.book_id, book.book_version)) {
			$('#mybook').append("<div class='ui-block-b block-center'><div class='img-left'> <a id = '" + book.book_id + "' href='#' class='openPopup' data-rel='popup'><img src='img/Book-icon.png'></a><div class='div-update'><p>Update</p></div></div><div class='content-right'><span>Title: </span><span>" + book.title + "<br></span><span>Version: </span><span>" + book.book_version + "</span></div></div>");
		}
		else {
			$('#mybook').append("<div class='ui-block-b block-center'><div class='img-left'> <a id = '" + book.book_id + "' onclick = 'launchFile(" + book.book_id + ")'><img src='img/Book-icon.png'></a></div><div class='content-right'><span>Title: </span><span>" + book.title + "<br></span><span>Version: </span><span>" + book.book_version +"</span></div></div>");
		}
	}
	openPopup();
}
/*
* launchFile: open an epub file via iBooks
*/
function launchFile(id) {
    alert('launchfile...');
    var book = JSON.parse(window.localStorage.getItem("book_" + id));
    alert('file title : ' + book.title);
    alert('file url : ' + book.fullPath);
    LaunchFile(book.fullPath); 
}
/*
*	Click on book which is needed to upload, popup appear
*/
function openPopup() {
	$('.openPopup').click(function() {
        var _this = $(this);
        var book_id = _this.attr('id');
        $('#popupDialog').popup('open');
        $('#updateNewVersion').off('click').click(function() {
            alert(_this.attr('id'));
            downloadFile(book_id);
        });
        $('#openOldVersion').off('click').click(function() {
            launchFile(book_id);
        });
    });
}
/*
* checkUpdate will compare data on localstorage and data on server, then return the result
*/
function checkUpdate(id, book_version) {
 	for (var i = 0; i < _data.length; i++) {
 		if (_data[i].book_id == id) {
 			if (_data[i].book_version != book_version) {
 				return true;
 			}
 		}
 	}
 	return false;
}
/*
*	downloadFile function
*/
/*
*   getBook(id) was called when a file download success.
*   a variable's name allFile is a phonegap's local storage, it will store all of book which is dowloaded on device.
*/
function getBook(id, fullPath) {
    try {
        $.ajax({
            url: "http://phanhuutho.com/thesis/test?id=" + id,
            type: 'POST',
            dataType: 'json',
            error: function (data) {
                console.log("App launch error", data);
            },
            success: function (data) {
                alert("getBook success!!");
                data.fullPath = fullPath; 
                var localData = JSON.stringify(data);
                window.localStorage.setItem("book_" + id, localData);
                var getlocalData = JSON.parse(localStorage.getItem('book_'+id));
            	getDataFromServer();
            }
        });
    } catch (err) {
        // err
    } 
}     
function downloadFile(id) {
    _book_id = id;
    window.requestFileSystem(
        LocalFileSystem.PERSISTENT,
        0,
        onRequestFileSystemSuccess,
        fail
    );
}

function onRequestFileSystemSuccess(fileSystem) {
    fileSystem.root.getFile(
        'dummy.html',
        {create: true, exclusive: false},
        onGetFileSuccess,
        fail
    );
}

function onGetFileSuccess(fileEntry) {
    alert('onGetFileSuccess! -->'+ _book_id);
    var path = fileEntry.toURL().replace('dummy.html', '');
    var fileTransfer = new FileTransfer();
    fileEntry.remove();
    
    fileTransfer.download(
        'http://phanhuutho.com/thesis/epub/index/export-epub/id/'+ _book_id,
        path + 'book_' + _book_id + '.epub',
        function(file) {
            alert('download complete: ' + file.toURI());
            getBook(_book_id, file.toURI());
            showLink(file.toURI());
        },
        function(error) {
            alert('download error source ' + error.source);
            alert('download error target ' + error.target);
            alert('upload error code: ' + error.code);
        }
    );
}

function showLink(url) {
    alert(url);
}

function fail(evt) {
    alert(evt.target.error.code);
}

/* When this function is called, PhoneGap has been initialized and is ready to roll */
function onDeviceReady() {
    // alert('device ready!');
    // window.localStorage.clear();
}